package com.leo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 * @author du
 */
public class NioServer {
    public static void main(String[] args) throws IOException {

        //ByteBuffer readBuffer = ByteBuffer.allocateDirect(1024);
        ByteBuffer writeBuffer = ByteBuffer.allocateDirect(1024);

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //serverSocketChannel.bind(new InetSocketAddress(7000));
        serverSocketChannel.socket().bind(new InetSocketAddress(7000));

        serverSocketChannel.configureBlocking(false);

        Selector selector = Selector.open();

        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);


        while (true) {
            //
            if (selector.select(1000) == 0) {
                //System.out.println("服务器等待1s无连接...");
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                iterator.remove();

                if (selectionKey.isAcceptable()) {
                    //ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    System.out.println("服务器已连接");
                }

                if (selectionKey.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();

                    ByteBuffer readBuffer = (ByteBuffer) selectionKey.attachment();
                    socketChannel.read(readBuffer);
                    System.out.println("接收数据: " + new String(readBuffer.array()));
                }
            }
        }
    }
}
